<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', '二维码列表']" />
    <a-card class="general-card" title="二维码列表">
      <formCom
        ref="formComDom"
        :option="searchOption"
        :key-count="state.keyCount"
        @serachFn="searchFn"
      />
      <div class="right-btn">
        <el-button plan type="" @click="actionFn('creatImg', {})"
          >生成图片</el-button
        >
        <el-button plan type="primary" @click="actionFn('add', {})"
          >新增二维码</el-button
        >
      </div>
      <kxTable
        :table-data="list"
        :column-list="columnList"
        border
        @selection-change="handleSelectionChange"
      >
        <template #status="{ row }">
          <span :class="{ 'used-status': row.status == '1' }">
            {{ row.status == '0' ? '未使用' : '已使用' }}
          </span>
        </template>
        <template #options="{ row }">
          <!-- <el-button link type="primary" @click="actionFn('edit', row)">编辑</el-button> -->
          <el-button link plan type="danger" @click="actionFn('del', row)"
            >删除</el-button
          >
        </template>
      </kxTable>
      <Pagination
        v-model:limit="pageSize"
        v-model:page="currentPage"
        :total="total"
        @pagination="getList()"
        @pagination-size-change="getList(1)"
      />

      <!-- 新增二维码弹框 -->
      <el-dialog
        v-model="showAddModal"
        :title="titleType[dialogType]"
        width="600px"
      >
        <el-form :model="newItem" label-width="100px">
          <formCom
            ref="formComDom"
            :option="option"
            :key-count="state.keyCount"
            @submitFn="submitFn"
            @cancle-fn="closeDialog"
          />
        </el-form>
        <!-- <template #footer>
          <span class="dialog-footer">
            <el-button @click="onCancel">取 消</el-button>
            <el-button type="primary" @click="onConfirm">确 定</el-button>
          </span>
        </template> -->
      </el-dialog>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { useList } from '@/use/index';
  import {
    qrcodeListApi,
    qrcodeGenerateApi,
    qrcodeDownloadApi,
    qrcodeUploadApi,
    qrcodeDelApi,
  } from '@/utils/apiConfig';
  import { useUserStore } from '@/store';
  import { baseTypeList } from './table';
  const userStore = useUserStore();

  const router = useRouter();
  const route = useRoute();
  const {} = route.query;
  const state = reactive({ keyCount: 1 });
  const searchOption = reactive({
    labelWidth: '80px',
    isBetween: false,
    position: 'left',
    formList: [
      {
        label: '标签code',
        val: '',
        field: 'labelCode',
        type: 'input',
        width: '300px',
        rightMargin: true,
      },
      {
        label: '状态',
        val: '',
        field: 'status',
        type: 'select',
        width: '300px',
        rightMargin: true,
        chooseList: [
          { label: '未使用', value: 0 },
          { label: '已使用', value: 1 },
        ],
      },
      {
        label: '标签类型',
        val: '',
        field: 'labelType',
        type: 'select',
        width: '300px',
        rightMargin: true,
        chooseList: baseTypeList,
      },
    ],
    showSreach: true,
  });
  const {
    searchForm,
    list,
    listLoading,
    total,
    currentPage,
    pageSize,
    getList,
    handleSearch,
    resetSearch,
  } = useList(qrcodeListApi);
  if (!searchForm.value) {
    searchForm.value = {
      deviceName: '', // 与后端搜索参数一致
    } as any;
  }

  const titleType: any = {
    add: '新增二维码',
    edit: '编辑二维码',
  };
  const option = reactive({
    labelWidth: '190px',
    isBetween: false, // false = float 布局
    showSubmit: true,
    position: 'left',
    // submitName: '新增资产',
    formList: [
      {
        label: '标签(多个用逗号隔开)',
        val: '',
        field: 'labelCodes',
        type: 'input',
        width: '100%',
        rightMargin: true,
        inputType: 'textarea',
        require: true,
        maxlength: 10000,
      },
      {
        label: '类型',
        val: '',
        field: 'labelType',
        type: 'select',
        width: '100%',
        rightMargin: true,
        require: true,
        chooseList: baseTypeList,
      },
    ],
  });
  const multipleSelection = ref([]);
  function handleSelectionChange(val: any) {
    const codes = val.map((item: any) => item.labelCode);

    multipleSelection.value = codes;
    console.log('过滤后', multipleSelection.value);
  }

  const showAddModal = ref(false);
  const columnList = reactive([
    {
      selection: true,
      width: '55',
    },
    {
      label: '标签code',
      prop: 'labelCode',
      minWidth: '120px',
    },
    {
      label: '创建时间',
      prop: 'createdTime',
      minWidth: '120px',
    },
    {
      label: '创建人',
      prop: 'createdBy',
      minWidth: '120px',
    },
    {
      label: '类型',
      prop: 'labelType',
      minWidth: '120px',
      formatter(row: any) {
        return baseTypeList.find((item: any) => item.value == row.labelType)
          ?.label;
      },
    },
    {
      label: '状态',
      prop: 'status',
      minWidth: '120px',
    },

    {
      slot: 'operation',
      width: '130',
      label: '操作',
      prop: 'options',
      notooltip: true,
      fixed: 'right',
    },
  ]);

  async function inits() {
    await getList();
    console.log('搜索参数', list.value);
    userStore.setQrcodeList(list.value);
  }
  function searchFn(obj: any) {
    searchForm.value = { ...(searchForm.value || {}), ...obj };
    inits();
  }
  function closeDialog() {
    showAddModal.value = false;
    option.formList.forEach((item) => {
      item.val = '';
    });
    state.keyCount += 1;
  }
  function submitFn(obj: any) {
    console.log(111111, obj);
    // list.value.push(obj);
    const { labelCodes, labelType } = obj;
    let labelCodesArray = [];
    try {
      const processedLabelCodes = labelCodes.replace(/，/g, ','); // 替换中文逗号为英文逗号
      labelCodesArray = processedLabelCodes.split(',');
      console.log('标签数组:', labelCodesArray);
    } catch (error: any) {
      ElMessage({
        message: '标签格式有误，请检查后重新输入',
        type: 'warning',
      });
      return;
    }

    if (dialogType.value === 'add') {
      qrcodeUploadApi({
        labelCodes: labelCodesArray,
        labelType,
      })
        .then((res: any) => {
          if (res.code === 200) {
            inits();
            ElMessage({
              message: '新增二维码成功',
              type: 'success',
            });
          }
        })
        .catch((err) => {
          console.log('add-err', err);
        });
    }
    closeDialog();
  }

  // 弹框与表单

  const newItem = ref({
    departmentName: '',
    departmentType: '',
    desc: '',
    tag: '',
  });
  const dialogType = ref('add');
  const dialogItem = ref({});
  function downloadFile(url: string, filename: string) {
    try {
      // 创建一个隐藏的 a 标签
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      link.target = '_blank';
      link.style.display = 'none';

      // 添加到页面并点击
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);

      ElMessage({ message: '开始下载二维码文件', type: 'success' });
    } catch (error: any) {
      ElMessage.error('下载失败: ' + error.message);
    }
  }

  function actionFn(type: string, item: any) {
    console.log(type, item);
    dialogType.value = type;
    dialogItem.value = item;
    switch (type) {
      case 'creatImg':
        console.log('生成二维码', multipleSelection.value);
        // 简单的 blob 下载函数

        qrcodeGenerateApi({
          labelCode: multipleSelection.value,
          logoUrl:
            'https://aisearch.cdn.bcebos.com/homepage/dashboard/ai_picture_create/13.png',
          companyName: '福建股份有限公司',
        }).then((res: any) => {
          if (res.code === 200) {
            const url = res.data;
            window.open(url, '_blank');
            // downloadFile(url, 'qrcode_images.zip');
          }
        });
        break;
      case 'add':
        showAddModal.value = true;
        break;
      case 'del':
        console.log(item.departmentName);
        ElMessageBox.confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            console.log('del-api');
            const id = item?.id;
            qrcodeDelApi({ addPath: id })
              .then((res) => {
                console.log('del-res', res);
                inits();
                ElMessage({
                  message: '删除二维码成功',
                  type: 'success',
                });
              })
              .catch((err) => {
                console.log('del-err', err);
              });
          })
          .catch(() => {});
        break;

      case 'edit':
        console.log('edit', item);
        option.formList.forEach((one) => {
          one.val = item[one.field];
        });
        state.keyCount += 1;
        showAddModal.value = true;
        break;

      default:
        break;
    }
  }

  onMounted(() => {
    inits();
  });
</script>

<style lang="less" scoped>
  .container {
    padding: 20px;
  }

  .container {
    padding: 20px;
  }

  .used-status {
    color: green;
  }
</style>
